package com.fingard.dsp.bank.directbank.bony02;


import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.math.BigDecimal;
import java.util.Date;

public class BONY02Transaction extends BONY02Base implements ITransaction {

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ats对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();// 写返回ATS的统一头部信息
        //赋值通用参数
        transCode = "DealQueryDtl";
        queryStartNo = "1";
        //每页条数，银行建议不超过60
        queryNum = "50";
        int nowReadedCounts = 0;//已读总笔数
        try {
            boolean tmpQryNext = true;
            while (tmpQryNext) {//分页查询
                //写入报文
                XmlTextWriter xmlWriter = new XmlTextWriter();
                seqNo = getQryTransID();
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("body");
                xmlWriter.writeStartElement("entity");
                xmlWriter.writeElementString("accountCode", p_req7516.actNum);
                xmlWriter.writeElementString("acct_seqno", "");
                xmlWriter.writeElementString("beginDate", Format.Date10Format.format(Format.Date8Format.parse(p_req7516.dateFrom)));
                xmlWriter.writeElementString("endDate", Format.Date10Format.format(Format.Date8Format.parse(p_req7516.dateTo)));
                xmlWriter.writeElementString("pageNo", queryStartNo);
                xmlWriter.writeElementString("pageCount", queryNum);
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                //发送银行前置机
                //String[] tmpStrRet = new String[]{"",""};
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                //赋值返回ats
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    //String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response><header><resTime>2019-06-21 19:19:48</resTime><tradeCode>DealQueryDtl</tradeCode><serialId>2020082239356865</serialId><corpCode>B0004551908</corpCode></header><body><entity><retCode>000000</retCode><retMsg>交易成功</retMsg></entity><list><entity><detailCode>2020-08-22E6601452830166010123090000002911.00</detailCode><accountCode>660101230900000029</accountCode><accountName>TESTB0004551908</accountName><otherAccount>660101230900000268</otherAccount><otherName>对公测试账户1111</otherName><otherDeposit>云浮新兴支行</otherDeposit><tradeSign>1</tradeSign><tradeMoney>1.0</tradeMoney><remainMoney>104132.4</remainMoney><tradeTime>2020-08-22 19:47:06</tradeTime><tradeSummary>测试</tradeSummary><index>202008221</index></entity><entity><detailCode>2020-08-220122974660101230900000029050000000.00</detailCode><accountCode>660101230900000029</accountCode><accountName>TESTB0004551908</accountName><otherAccount></otherAccount><otherName></otherName><otherDeposit></otherDeposit><tradeSign>0</tradeSign><tradeMoney>5.0E7</tradeMoney><remainMoney>5.01041324E7</remainMoney><tradeTime>2020-08-22 19:12:11</tradeTime><tradeSummary>工程款</tradeSummary><index>202008222</index></entity><entity><detailCode>2020-08-22E6601482556966010123090000002912.00</detailCode><accountCode>660101230900000029</accountCode><accountName>TESTB0004551908</accountName><otherAccount>660101230900000268</otherAccount><otherName>对公测试账户1111</otherName><otherDeposit>云浮新兴支行</otherDeposit><tradeSign>1</tradeSign><tradeMoney>2.0</tradeMoney><remainMoney>5.01041304E7</remainMoney><tradeTime>2020-08-22 20:13:32</tradeTime><tradeSummary>测试-CC00000337</tradeSummary><index>202008223</index></entity></list></body></response>";
                    //tmpBkReader = loadBankRespXmlReader(xml, tmpSbMsg);
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String retCode = tmpBkReader.getFirstText("/response/body/entity/retCode");
                        String respMsg = tmpBkReader.getFirstText("/response/body/entity/retMsg").trim();
                        int curQueryNum = 0;//本次查询返回笔数
                        if (retCode != null && isActiveRetCode(retCode)) {
                            while (tmpBkReader.read("/response/body/list/entity")) {
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                String tranDate = tmpBkReader.readedXElement.getSingleText("tradeTime"); //格式为yyyy-MM-dd hh:mm:ss
                                tmpRetDetail.tranDate = tranDate.substring(0, 10);
                                tmpRetDetail.tranTime = tranDate;
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日没有返回就用交易日
                                tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("accountCode");//账号
                                if (!tmpRetDetail.actNum.equals(p_req7516.actNum)) {
                                    String tmpInfo = "银行返回的账号" + tmpRetDetail.actNum + "与请求账号" + p_req7516.actNum + "不符";
                                    retAts.writeRespCode("-1");
                                    retAts.writeRespInfo(tmpInfo);
                                    retAts.writeEnd();
                                    return retAts;
                                }
                                tmpRetDetail.urid = tmpBkReader.readedXElement.getSingleText("detailCode");//明细主键
                                tmpRetDetail.accBal = Format.DecimalAmtFormat.format(new BigDecimal(tmpBkReader.readedXElement.getSingleText("remainMoney")));//账户余额
                                tmpRetDetail.cur = p_req7516.actCur; //币种
                                tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("otherAccount");//对方账号
                                tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("otherName");//对方户名
                                tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("tradeSummary");//摘要
                                tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("otherDeposit");//银行
                                //借贷标志 必填0-借（收入）1-贷（支出）,ats只有支出1和收入2
                                tmpRetDetail.tranAmt = Format.DecimalAmtFormat.format(new BigDecimal(tmpBkReader.readedXElement.getSingleText("tradeMoney")));//交易金额
                                String dcFlag = tmpBkReader.readedXElement.getSingleText("tradeSign");
                                switch (Integer.parseInt(dcFlag)) {
                                    case 0: {//借
                                        tmpRetDetail.cdFlag = "2";
                                        break;
                                    }
                                    case 1: {//贷
                                        tmpRetDetail.cdFlag = "1";
                                        break;
                                    }
                                    default:
                                        retAts.writeRespCode("-1");
                                        retAts.writeRespInfo("银行返回借贷标志无法识别，请核对！");
                                        retAts.writeEnd();
                                        return retAts;
                                }
                                retAts.writeRetDetail(tmpRetDetail);
                                curQueryNum++;
                            }
                            nowReadedCounts += curQueryNum;
                            if (curQueryNum < 50) {
                                tmpQryNext = false;
                                if (nowReadedCounts == 0) {
                                    retAts.writeRespCode("0");
                                    retAts.writeRespInfo("银行返回明细为空");
                                    break;
                                }
                            } else {
                                queryStartNo = String.valueOf(Integer.valueOf(queryStartNo) + 1);
                            }
                        } else {
                            tmpQryNext = false;
                            retAts.writeRespCode(retCode);
                            retAts.writeRespInfo(respMsg);
                        }
                    } else {
                        tmpQryNext = false;
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpSbMsg.toString());
                    }
                } else {
                    tmpQryNext = false;
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpStrRet[1]);
                }
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
